package utils

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

/*
	将config配置文件中的变量全部引用到此
*/
var GlobalConfig *viper.Viper
var (
	AppMode            string
	HttpPort           string
	JwtKey             string
	Host               string
	User               string
	Pwd                string
	Port               int
	Dbname             string
	Db                 string
	EndpointAli        string
	AccessKeyIdAli     string
	AccessKeySecretAli string
	BucketNameAli      string
	Endpoint           string
	AccessKeyId        string
	AccessKeySecret    string
	BucketName         string
	LogPath            string
)

func init() {
	GlobalConfig = initConfig()
	go dynamicConfig()
}

//初始化viper配置管理
func initConfig() *viper.Viper {
	GlobalConfig = viper.New()
	//GlobalConfig.SetConfigFile("D:\\go\\src\\ginblog\\config\\config.yaml") //直接定义死配置文件路径
	//viper.SetDefault("fileDir", "./")
	GlobalConfig.SetConfigName("config")
	GlobalConfig.SetConfigType("yaml")
	GlobalConfig.AddConfigPath("config/")
	if err := GlobalConfig.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			fmt.Println("配置文件不存在", err)
		} else {
			fmt.Println("配置文件存在其他错误", err)
		}
	}
	AppMode = GlobalConfig.GetString("System.AppMode")
	HttpPort = GlobalConfig.GetString("System.HttpPort")
	JwtKey = GlobalConfig.GetString("System.JwtKey")
	Db = GlobalConfig.GetString("Mysql.Db")
	Dbname = GlobalConfig.GetString("Mysql.Dbname")
	Host = GlobalConfig.GetString("Mysql.Host")
	User = GlobalConfig.GetString("Mysql.User")
	Pwd = GlobalConfig.GetString("Mysql.Pwd")
	Port = GlobalConfig.GetInt("Mysql.Port")
	EndpointAli = GlobalConfig.GetString("CloudOss.endpoint")
	AccessKeyIdAli = GlobalConfig.GetString("CloudOss.accessKeyId")
	AccessKeySecretAli = GlobalConfig.GetString("CloudOss.accessKeySecret")
	BucketNameAli = GlobalConfig.GetString("CloudOss.bucketName")
	Endpoint = GlobalConfig.GetString("CloudQnOss.endpoint")
	AccessKeyId = GlobalConfig.GetString("CloudQnOss.accessKeyId")
	AccessKeySecret = GlobalConfig.GetString("CloudQnOss.accessKeySecret")
	BucketName = GlobalConfig.GetString("CloudQnOss.bucketName")
	//LogPath = GlobalConfig.GetString("Log.logPath")
	return GlobalConfig
}

//监控并重新读取配置文件
func dynamicConfig() {
	GlobalConfig.WatchConfig() //实时监控配置文件变化
	GlobalConfig.OnConfigChange(func(e fsnotify.Event) {
		//配置文件发生变更之后会调用的回调函数
		fmt.Println("config file changed: ", e.Name)
	})
}
